import React from 'react'
import { Form, Input, Button, message } from 'antd'
import { UserOutlined, LockOutlined } from '@ant-design/icons'
import { loginApi } from '../api/index'
import { useNavigate } from 'react-router-dom'
import './less/Login.less'

function Login() {
  const navigate = useNavigate()
  const onFinish = (values) => {
    loginApi(values)
      .then((res) => {
        if (res.errCode) {
          message.error(res.message)
        } else {
          message.success(res.message)
          // 存储登录信息
          localStorage.setItem('cms-token', res.data['cms-token'])
          localStorage.setItem('username', res.data['username'])
          localStorage.setItem('editable', res.data['editable'])
          localStorage.setItem('player', res.data['player'])
          localStorage.setItem('avatar', res.data['avatar'])
          setTimeout(() => {
            navigate('/')
          }, 1500)
        }
      })
      .catch((error) => {
        message.error(error)
      })
  }
  const toRegister = () => {
    navigate('/register')
  }
  const onFinishFailed = () => {}
  return (
    <div className="login">
      <Form
        className="login-box"
        name="basic"
        labelCol={{ span: 5 }}
        wrapperCol={{ span: 18 }}
        initialValues={{ remember: true }}
        onFinish={onFinish}
        onFinishFailed={onFinishFailed}
        autoComplete="off">
        <p class="title">登录页面</p>
        <Form.Item label="用户名" name="username">
          <Input prefix={<UserOutlined />} size="large" />
        </Form.Item>

        <Form.Item label="密码" name="password">
          <Input.Password prefix={<LockOutlined />} size="large" />
        </Form.Item>

        <p className="action-font" onClick={toRegister}>
          无账号？前往注册
        </p>

        <Form.Item className="login-btn" wrapperCol={{ offset: 10 }}>
          <Button type="primary" htmlType="submit" size="large">
            登录
          </Button>
        </Form.Item>
      </Form>
    </div>
  )
}

export default Login
